package com.dcxs.shop.module.order.controller;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.NumberUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dcxs.shop.common.utils.R;
import com.dcxs.shop.module.order.dto.Cart;
import com.dcxs.shop.module.order.entity.JsCart;
import com.dcxs.shop.module.order.entity.JsExpress;
import com.dcxs.shop.module.order.service.IJsCartService;
import com.dcxs.shop.module.order.service.IJsExpressService;
import com.dcxs.shop.module.product.entity.*;
import com.dcxs.shop.module.product.service.*;
import com.dcxs.shop.module.supplier.entity.JsSupplier;
import com.dcxs.shop.module.user.entity.JsUsr;
import com.dcxs.shop.module.user.service.IJsUsrService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.List;

/**
 * <p>
 * 购物车表 前端控制器
 * </p>
 *
 * @author zzh
 * @since 2020-03-01
 */
@RestController
@RequestMapping("/order/js-cart")
public class JsCartController {


    @Autowired
    private IJsCartService cartService;

    @Autowired
    private IJsUsrService usrService;

    @Autowired
    private IJsProductPriceService productPriceService;

    @Autowired
    private IJsProductService productService;

    @Autowired
    private IJsProductSpecificationService specificationService;

    @Autowired
    private IJsProductPayService productPayService;

    @Autowired
    private IJsProductPicService productPicService;

    @Autowired
    private IJsExpressService expressService;



    @RequestMapping("/addCart")
    public R addCart(@RequestBody JsCart jsCart, HttpServletRequest request){
        Integer  userId = usrService.getUserIdByPhone(request.getAttribute("userId").toString());
        Integer count = cartService.count(new QueryWrapper<JsCart>().eq("usr_id",userId)
                .eq("product_id",jsCart.getProductId()).eq("specification_id",jsCart.getSpecificationId()).eq("price_id",jsCart.getPriceId()));
        if(count>0){
            //说明存在
            JsCart jsCart1 = cartService.getOne(new QueryWrapper<JsCart>().eq("usr_id",userId)
                    .eq("product_id",jsCart.getProductId()).eq("specification_id",jsCart.getSpecificationId()).eq("price_id",jsCart.getPriceId()));
            jsCart1.setNum(jsCart1.getNum()+1);
            if(null!=jsCart.getShareUsrId()){
                jsCart1.setShareUsrId(jsCart1.getShareUsrId());
            }
            cartService.updateById(jsCart1);
        }else {
            jsCart.setUsrId(userId);
            jsCart.setCreateTime(LocalDateTime.now());
            if(null!=jsCart.getShareUsrId()){
                jsCart.setShareUsrId(jsCart.getShareUsrId());
            }
            cartService.save(jsCart);
        }
        return new R();
    }

    @GetMapping("/selectCar")
    public R selectCar(HttpServletRequest request){
        Integer  userId = usrService.getUserIdByPhone(request.getAttribute("userId").toString());
        List<JsCart> list = cartService.list(new QueryWrapper<JsCart>().eq("usr_id",userId));
        BigDecimal totalPrice = new BigDecimal("0");
        BigDecimal totalWeight = new BigDecimal("0");
        if(CollectionUtil.isNotEmpty(list)){
            Iterator<JsCart> iterator = list.iterator();
            while (iterator.hasNext()){
                JsCart jsCart = iterator.next();
                JsProduct product = productService.getById(jsCart.getProductId());
                JsProductSpecification specification = specificationService.getById(jsCart.getSpecificationId());
                if(null!=product){
                    if(1==product.getState()&&null!=specification){
                        //查询支付方式
                        List<JsProductPay> payList = productPayService.list(new QueryWrapper<JsProductPay>().eq("product_id",product.getId()));
                        if(CollectionUtil.isNotEmpty(payList)){
                            jsCart.setPayList(payList);
                        }
                        JsProductPrice productPrice = productPriceService.getById(jsCart.getPriceId());
                        //设置单价
                        if(StringUtils.isNotBlank(product.getSupplierName())&&null!=product.getSupplierId()){
                            JsSupplier supplier = new JsSupplier();
                            supplier.setName(product.getSupplierName());
                            supplier.setId(product.getSupplierId());
                            jsCart.setSupplier(supplier);
                        }
                        jsCart.setPrice(productPrice.getPrice());
                        //查询图片
                        List<JsProductPic> list1 = productPicService.list(new QueryWrapper<JsProductPic>().eq("product_id",product.getId()));
                        if(CollectionUtil.isNotEmpty(list1)){
                            jsCart.setProductPic(list1.get(0).getPicUrl());
                        }
                        jsCart.setProductName(product.getName());
                        jsCart.setSpecificationName(specification.getSpecification());
                        jsCart.setIsFreeShipping(product.getIsFreeShipping()==null?0:product.getIsFreeShipping());
                        //是否包邮
                        if(0==product.getIsFreeShipping()){
                            totalWeight=new BigDecimal(productPrice.getWeight()*jsCart.getNum()/1000).add(totalWeight);
                            jsCart.setWeight(NumberUtil.round(new BigDecimal(productPrice.getWeight()*jsCart.getNum()),2));
                        }
                        jsCart.setSpecificationDetailName(productPrice.getType());
                        totalPrice=totalPrice.add(productPrice.getPrice().multiply(new BigDecimal(jsCart.getNum())));
                    }else {
                        Console.log(jsCart.getSpecificationId()+"这个规格ID被删除或者该商品未上架");
                        iterator.remove();
                    }
                }
            }
        }
        List<JsExpress> list1 =expressService.list();
        BigDecimal firstPrice = new BigDecimal("0");
        BigDecimal addPrice = new BigDecimal("0");
        if(2==list1.size()){
            for(JsExpress express:list1){
                if(1==express.getType()){
                    firstPrice=NumberUtil.round(express.getFee(),2);
                }else {
                    addPrice=NumberUtil.round(express.getFee(),2);
                }
            }
        }
        JsUsr usr = usrService.getById(userId);
        BigDecimal points = usr.getBalance();
        Cart cart = Cart.builder().jsCart(list).totalPrice(totalPrice).firstPrice(firstPrice).addPrice(addPrice).points(points).build();
        return new R().put("data",cart);
    }


    @RequestMapping("/delete")
    public R delete(@RequestBody List<String> ids){
         cartService.removeByIds(ids);
         return R.ok();
    }

    @RequestMapping("/updateCount")
    public R updateCount(@RequestBody JsCart jsProduct){
        cartService.updateById(jsProduct);
        return R.ok();
    }

}
